package com.ukee.birthday.modules.controller;

import com.ukee.birthday.common.utils.JwtUtils;
import com.ukee.birthday.common.utils.R;
import com.ukee.birthday.common.validator.ValidatorUtils;
import com.ukee.birthday.common.validator.group.AddGroup;
import com.ukee.birthday.modules.entity.StaffEntity;
import com.ukee.birthday.modules.form.WxLoginForm;
import com.ukee.birthday.modules.service.SysUserTokenService;
import com.ukee.birthday.modules.service.WxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wx")
public class WxLoginController extends AbstractController {

    @Resource
    private WxUserService wxUserService;

    @Resource
    private SysUserTokenService tokenService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 微信用户登录
     */
    @PostMapping("/login")
    public Map<String,Object> login(@RequestBody WxLoginForm form) throws IOException {
        logger.info("login api,SysLoginForm={}",form);
        ValidatorUtils.validateEntity(form, AddGroup.class);

        //用户信息
        StaffEntity user = wxUserService.queryByUserName(form.getUsername(),form.getIdNumber());

        logger.info("login api,user={}",user);

        if(user == null){
            return R.error("用户名或身份证号错误！");
        }else {
//            if(user.getRoleId() != 2 && user.getRoleId() !=3){
//                return R.error("当前账号不是发餐人或员工！");
//            }
            if(!user.getNumber().equals(form.getNumber())){
                return R.error("工号错误！");
            }
        }

        //生成token，保存到数据库
        R r = tokenService.createToken(user.getId(),2);
        r.put("info",getUserInfoForm(user));

        //生成token
//        String token = jwtUtils.generateToken(user.getId());
//        UserInfoForm userInfoForm = new UserInfoForm().getUserInfo(user);
//        userInfoForm.setToken(token);
//        R r = R.ok().put("token",token);
//        r.put("info",userInfoForm);
        return r;
    }

    public Map<String,Object> getUserInfoForm(StaffEntity user){

        Map<String,Object> userInfoFrom = new HashMap<>();
        userInfoFrom.put("userId",user.getId());
        userInfoFrom.put("username",user.getUsername());
        userInfoFrom.put("telnum",user.getTelnum());
        userInfoFrom.put("birthday",user.getBirthday());
        userInfoFrom.put("avatar",user.getAvatar());
        userInfoFrom.put("idNumber",user.getIdNumber());
        userInfoFrom.put("number",user.getNumber());
        userInfoFrom.put("age",user.getAge());
        userInfoFrom.put("roleId",user.getRoleId());

        return userInfoFrom;
    }
}
